package models

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

const (
	weekDay = 7
)

type IpccConfQueue struct {
	ConfId     int       `orm:"description(配置Id);pk;auto"`
	Id         int       `orm:"description(队列Id);null"`
	AppId      string    `orm:"description(关联公司)"`
	Name       string    `orm:"description(队列名称)"`
	KeyIn      string    `orm:"description(入队按键,事件)"`
	QLen       int       `orm:"description(队列长度);column(queue_len);null"`
	DistribWay string    `orm:"description(分发方式);null"`
	Media      string    `orm:"description(入队等待音);null"`
	ActiveFrom time.Time `orm:"description(生效起始时间);null"`
	ActiveEnd  time.Time `orm:"description(生效结束时间);null"`
	//DayActive  [weekDay]string `orm:"description(生效星期)"`
	WaitTime   int       `orm:"description(入队后最长等待时间);null"`
	CreateTime time.Time `orm:"description(创建时间);auto_now_add; type(datetime)"`
}

func RegisterQueue() {
	orm.RegisterModel(new(IpccConfQueue))
}

func StoreQue(id int, appId, name, key, media, distrb string) error {

	nq := IpccConfQueue{
		Id:         id,
		AppId:      appId,
		Name:       name,
		KeyIn:      key,
		DistribWay: distrb,
		Media:      media,
		CreateTime: time.Now(),
	}

	o := orm.NewOrm()

	_, err := o.Insert(&nq)
	if err == nil {
		logs.Debug("create new queue:%v-%v,for company:%v", nq.Id, nq.Name, appId)
	} else {
		logs.Debug("queue:[%v]-[%v] of company:%v is exist", nq.Id, nq.Name, appId)
	}

	return err
}

func UpdateQue(id int, name, key, media, distrb string) error {

	nq := IpccConfQueue{
		Id:         id,
		KeyIn:      key,
		Name:       name,
		DistribWay: distrb,
		Media:      media,
	}

	if id == 0 {
		return nil
	}

	o := orm.NewOrm()

	if name != "" {
		_, err := o.Update(&nq, "Name")
		if err != nil {
			return err
		}
	}

	if key != "" {
		_, err := o.Update(&nq, "KeyIn")
		if err != nil {
			return err
		}
	}

	if media != "" {
		_, err := o.Update(&nq, "Media")
		if err != nil {
			return err
		}
	}

	if distrb != "" {
		_, err := o.Update(&nq, "DistribWay")
		if err != nil {
			return err
		}
	}

	return nil

}

func DelQue(id int, appId, name string) {

	n := &IpccConfQueue{
		Id:    id,
		AppId: appId,
		Name:  name,
	}

	if id == 0 {
		return
	}

	o := orm.NewOrm()
	_, err := o.Delete(n, "AppId", "Name")
	if err != nil {
		logs.Error("delete err:%v,%v", err, n)
	}
}

func LoadQueue(appId string, offset int) ([]*IpccConfQueue, error) {

	var res []*IpccConfQueue
	o := orm.NewOrm()

	n, err := o.QueryTable(new(IpccConfQueue)).Offset(offset*100).
		Filter("AppId", appId).
		Limit(100).
		All(&res)
	if n == 0 {
		logs.Debug("get Queue :%v ,err:%v", n, err)
		return res, errors.New("EOF")
	}

	return res, err
}
